package com.bbtShop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbtShop.config.BizException;
import com.bbtShop.core.model.*;
import com.bbtShop.dao.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 示例Service定义
 *
 * @author 189****3725
 * @date 2020/10/13 15:04
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public IPage<User> getLisUser(Integer pageNum, Integer pageSize, User user) {

        IPage<User> page = new Page<>(pageNum == null ? 1 : pageNum,
                pageSize == null ? 10 : pageSize);
        return userMapper.selectPage(page, new LambdaQueryWrapper<>());


    }

    public void addUpdateUser(User user) {

        if (user.getId() == null) {
            if (user.getName()==null) {
                throw new BizException("用户名不能为空");
            }
            user.setAddTime(new Date());
            if (user.getBirthday()==null){
                user.setBirthday(new Date());
                user.setMoney(BigDecimal.ZERO);
            }
            userMapper.insert(user);
        } else {
            userMapper.updateById(user);
        }

    }

    public void delUser(Ids ids) {
        userMapper.deleteBatchIds(ids.getIds());

    }

    public User getUserInfo(Integer id) {
        return userMapper.selectById(id);

    }

    public List<UserDto> getAllUser() {
        ArrayList<UserDto> userDtos = new ArrayList<>();
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<>());
        for (User user : users) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
            userDtos.add(userDto);
        }
        return userDtos;


    }
}